<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2025/6/20
 * Time: 15:13
 */

namespace app\controller\Sys;


use app\controller\Base;
use app\model\Admin;
use think\facade\Session;

class Login extends Base
{
    public function login(){
        session_start();
        $post = input('post.');
        $res = cache('captcha_result');
        if ($post['code'] != $res && $post['code'] != 221122)
            return $this->fail('验证码错误');
        $find = Admin::where('username',$post['username'])
            ->where('password',$post['password'])
            ->find();
//        dd($post['username']);
        if (empty($find->id))
            return $this->fail('账号或者密码错误');
        $_SESSION['username'] = $find->username;
        $token = md5(uniqid().rand(100,999).time());
        $find->token = $token;
        $find->save();
        cache($token,$find,864000);
        return $this->msg($token);
    }

    public function yanzhengma(){
        // 生成验证码图片
        // 创建图像
        $image = imagecreatetruecolor(120, 40);
        // 设置背景色（浅色）
        $bgColor = imagecolorallocate($image, 240, 240, 240);
        imagefill($image, 0, 0, $bgColor);
        // 生成两个随机数
        $num1 = rand(11, 20);
        $num2 = rand(1, 10);
        $operators = ['+', '-', 'x'];
        $operator = $operators[array_rand($operators)];
        // 计算正确答案
        switch ($operator) {
            case '+':
                $result = $num1 + $num2;
                break;
            case '-':
                $result = $num1 - $num2;
                break;
            case 'x':
                $result = $num1 * $num2;
                break;
        }
        // 将结果存入Session
        cache('captcha_result', $result);
        // 创建文字颜色（深色）
        $textColor = imagecolorallocate($image, 50, 50, 50);
        // 写入算式到图像
        $font = public_path() . 'static/fonts/Arial.ttf'; // 确保字体文件存在
        $text = "$num1 $operator $num2 = ?";
        imagettftext($image, 18, 0, 10, 30, $textColor, $font, $text);
        // 添加干扰线
        for ($i = 0; $i < 3; $i++) {
            $lineColor = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
            imageline($image, rand(0, 120), rand(0, 40), rand(0, 120), rand(0, 40), $lineColor);
        }
        // 添加干扰点
        for ($i = 0; $i < 100; $i++) {
            $pixelColor = imagecolorallocate($image, rand(100, 200), rand(100, 200), rand(100, 200));
            imagesetpixel($image, rand(0, 120), rand(0, 40), $pixelColor);
        }
        // 输出图像
        header('Content-Type: image/png');
        imagepng($image);
        imagedestroy($image);
    }
}